package com.intel.bluetooth;

import javax.bluetooth.*;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class DiscoveryService {

    public Set<RemoteDevice> findDevices() {

        Set<RemoteDevice> devicesDiscovered = new HashSet<RemoteDevice>();

        final Object inquiryCompletedEvent = new Object();

        devicesDiscovered.clear();

        DiscoveryListener listener = new DiscoveryListener() {
            public void inquiryCompleted(int discType) {
                System.out.println("#" + "搜索完成");
                synchronized (inquiryCompletedEvent) {
                    inquiryCompletedEvent.notifyAll();
                }
            }

            @Override
            public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
                try {
                    System.out.println("#" + remoteDevice.getFriendlyName(true) + " -> " + remoteDevice.getBluetoothAddress());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                devicesDiscovered.add(remoteDevice);
            }

            @Override
            public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
                System.out.println("#" + "servicesDiscovered");
            }

            @Override
            public void serviceSearchCompleted(int arg0, int arg1) {
                System.out.println("#" + "serviceSearchCompleted");
            }
        };

        synchronized (inquiryCompletedEvent) {
            try {
                LocalDevice ld = LocalDevice.getLocalDevice();

                System.out.println("#本机蓝牙名称:" + ld.getFriendlyName());

                boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);

                if (started) {
                    System.out.println("#" + "等待搜索完成...");
                    inquiryCompletedEvent.wait();
                    LocalDevice.getLocalDevice().getDiscoveryAgent().cancelInquiry(listener);
                    System.out.println("#发现设备数量：" + devicesDiscovered.size());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return devicesDiscovered;
    }

}
